# -*- coding: utf-8 -*-
import os
import json

import requests

from HearthStoneSpider.minapp.script.base import b


class Cards(object):
    __meta = 'cards'

    def __init__(self):
        self.headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer {}'.format(b.get_token())
        }

    def get_base_list(self):
        response = requests.get('https://cloud.minapp.com/oserve/v1/table/', headers=self.headers)
        return response.json()

    def init_database(self):
        init_json_path = os.path.join(os.path.abspath(os.path.dirname(os.getcwd()) + os.path.sep + "."),
                                      'init_json/cards.json')
        with open(init_json_path, 'r', encoding='utf-8') as f:
            payload = f.read()
        requests.post('https://cloud.minapp.com/oserve/v1/table/', headers=self.headers, json=json.loads(payload))
        return

    def run(self):
        base_lists = self.get_base_list()
        for objects in base_lists['objects']:
            if self.__meta in objects['name']:
                return objects['id']
        self.init_database()

    def update_data_to_minapp(self, card):
        table_id = self.run()
        payload = {
            'mana': card.get('mana'),
            'hp': card.get('hp'),
            'attack': card.get('attack'),
            'cname': card.get('cname'),
            'description': card.get('description'),
            'ename': card.get('ename'),
            'faction': card.get('faction'),
            'clazz': card.get('clazz'),
            'race': card.get('race'),
            'rarity': card.get('rarity'),
            'rule': card.get('rule'),
            'seriesAbbr': card.get('seriesAbbr'),
            'seriesName': card.get('seriesName'),
            'standard': card.get('standard'),
            'wild': card.get('wild'),
            'img': card.get('img'),
            'thumbnail': card.get('thumbnail')
        }
        response = requests.post('https://cloud.minapp.com/oserve/v1/table/{}/record/'.format(table_id),
                                 headers=self.headers, json=payload)
        print(response.status_code)


hs_cards = Cards()
